package cn.xsly.ymcc.mq.consumer;

import cn.xsly.ymcc.constants.MQConstants;
import cn.xsly.ymcc.domain.CourseOrder;
import cn.xsly.ymcc.dto.PayResultVo;
import cn.xsly.ymcc.service.ICourseOrderService;
import cn.xsly.ymcc.util.AssertUtil;
import com.alibaba.fastjson.JSON;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;


@Component
@RocketMQMessageListener(topic = MQConstants.TOPIC_PAY,
        selectorExpression = MQConstants.TAGS_PAY,
        consumerGroup = MQConstants.CONSUMER_GROUP_PAY,
        messageModel = MessageModel.BROADCASTING)
public class PayResultConsumer implements RocketMQListener<MessageExt> {


    @Autowired
    private ICourseOrderService courseOrderService;

    @Override
    public void onMessage(MessageExt message) {
        byte[] body = message.getBody();
        //数据的转换
        String str = new String(body);
        PayResultVo payResultVo = JSON.parseObject(str, PayResultVo.class);
        //1.为了防止重复消费，查询一下是否已经创建过支付单
        CourseOrder courseOrder = courseOrderService.selectByOrderSn(payResultVo.getOrderSn());
        AssertUtil.isNotNull(courseOrder, "无效的订单号");

        //更新订单状态
        if (courseOrder.getStatusOrder() != 1) {
            courseOrder.setStatusOrder(1);
            courseOrder.setUpdateTime(new Date());
            courseOrderService.updateById(courseOrder);
        }
    }
}